package com.primaryedu.ui.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ClearCacheRequest;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.HomenewsAdapter;
import com.primaryedu.bean.AccountBean;
import com.primaryedu.bean.HomenewsBean;
import com.primaryedu.bean.NewsBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.encrpy.EncrpyUtils;
import com.primaryedu.ui.BaseFragment;
import com.primaryedu.ui.LoginActivity;
import com.primaryedu.ui.MainActivity;
import com.primaryedu.ui.news.NewsActivity;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings.Global;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import okhttp3.Call;

/**
 * 新闻资讯
 *
 * @author jun.wang
 * @description
 * @data 2016年12月13日
 */
public class NewsFragment extends BaseFragment implements OnHeaderRefreshListener, OnFooterRefreshListener {

    private View view;
    MyListView newsListView;
//    NewsAdapter newsAdapter ;

    HomenewsAdapter newsAdapter;
    private List<HomenewsBean.DataBean.ListBean> newsLists;
    private List<NewsBean> tempLists = new ArrayList<>();
    protected RequestQueue requestQueue = null;

    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
//                    if (null != GlobalData.newsLists && GlobalData.newsLists.size() != 0) {
//                        newsAdapter = new ExerciseAdapter(getActivity(), Utils.getExerciseList(GlobalData.newsLists));
//                        newsListView.setAdapter(newsAdapter);
//                    }
                    if (null != homenewsBean.getData().getList() && homenewsBean.getData().getList().size() != 0) {
                        if (newsLists == null) {
                            newsLists = homenewsBean.getData().getList();
                            newsAdapter = new HomenewsAdapter(getActivity(), newsLists);
                            newsListView.setAdapter(newsAdapter);
                        }else {
                            newsLists.addAll(homenewsBean.getData().getList());
                            newsAdapter.notifyDataSetChanged();
                        }
                    }else {
                        if( newsLists!=null && newsLists.size()>0){
                            showToast( "亲，到底了");
                        }else{
                            showToast("亲，暂无数据");
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private PullToRefreshView pullToRefreshView;
    private int page = 1;
    private HomenewsBean homenewsBean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_new, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init();

        requestNews();

//		getNews() ;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_new;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

    }

    @Override
    protected void initData() {

    }

    private void init() {
        requestQueue = Volley.newRequestQueue(getActivity());
//		File cacheDir = new File(getActivity().getCacheDir(), "volley");
//        DiskBasedCache cache = new DiskBasedCache(cacheDir);
//        requestQueue.start();
//        requestQueue.add(new ClearCacheRequest(cache, null));

        newsListView = (MyListView) view.findViewById(R.id.newsListView);
        ((TextView) view.findViewById(R.id.title)).setText("新闻");
        view.findViewById(R.id.back).setVisibility(View.GONE);

        newsListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                StringBuilder builder = new StringBuilder();
                builder.append(Contants.news_api);
                builder.append(newsLists.get(position).getId() + "/" + GlobalData.getUserId(getActivity()));
                System.out.println("builder==" + builder.toString());
                Intent intent = new Intent(getActivity(), NewsActivity.class);
                intent.putExtra("urlStr", builder.toString());
                intent.putExtra("type", "0");
                intent.putExtra("newId", newsLists.get(position).getId());
                startActivity(intent);
            }
        });

        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    private void requestNews() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("status", "1");
        params.put("pageSize", "10");
        params.put("pageNo", page + "");
        OkHttpUtils.post()//
                .url(Contants.getNews)
                .params(params)//
                .build()//
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println("response=news=" + response);
                        Gson gson = new Gson();
                        homenewsBean = gson.fromJson(response, HomenewsBean.class);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                handler.sendEmptyMessage(1001);
                            }else {
                                showToast("新闻获取失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
       /* StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getNews,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=new=" + response);
                        Gson gson = new Gson();
                        homenewsBean = gson.fromJson(response, HomenewsBean.class);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                *//*String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                newsLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<NewsBean>>() {
                                        }.getType());
//						    	  tempLists.addAll(newsLists) ;
                                GlobalData.newsLists.addAll(newsLists);*//*
                                handler.sendEmptyMessage(1001);
//                                System.out.println("newsLists==" + listStr);
                            }else {
                                showToast("新闻获取失败");
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
//			            //在这里设置需要post的参数
//			            Map<String, String> map = new HashMap<String, String>();  
//			            map.put("status", "1"); 
//			            map.put("pageSize", "10");  
//			            map.put("pageNo", page+"") ;
//			            return map;
//					builder.append("&columnId=7f58c481e48440148472cd2cd38b7c85") ;
//					builder.append("&sord=desc") ;
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                return map;

            }
        };
        requestQueue.add(stringRequest);*/
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                page++;
                requestNews();
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestNews();
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                showToast("数据刷新完成");
            }

        }, 1500);
    }

    private void getNews() {
        StringBuilder builder = new StringBuilder();
        builder.append(Contants.getNews);
        builder.append("?pageSize=10");
        builder.append("&pageNo=1");
        builder.append("&columnId=7f58c481e48440148472cd2cd38b7c85");
        builder.append("&sord=desc");

        StringRequest stringRequest = new StringRequest(Request.Method.GET,
                builder.toString(), new Response.Listener<String>() {

            @Override
            public void onResponse(String arg0) {

                System.out.println("getNews===" + arg0);

                try {
                    JSONObject json = new JSONObject(arg0);
                    String reason = json.getString("reason");
                    int result = json.getInt("result");
                    String data = json.getString("data");

                    if (result == 1) {

//				    	  AccountBean bean = new Gson().fromJson(data,
//			    					new TypeToken<AccountBean>() {
//			    					}.getType());
//				    	  System.out.println("bean=="+bean);
//				    	  GlobalData.accountBean = bean ;
//				    	  handler.sendEmptyMessage(1001) ;
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError arg0) {
//	            showToast(ErrorMsg.net_error) ;
            }
        });
        //为此get请求设置一个Tag属性
        stringRequest.setTag("GET_TAG");
        //将此get请求加入
        requestQueue.add(stringRequest);
    }

}
